import { TablePaginationConfig } from "antd";
import { FilterValue, SortOrder, SorterResult } from "antd/es/table/interface";
import { useMemo, useState } from "react";

/**
 * @returns
 */
const useTableSorter = (): any[] => {
  // 排序信息
  const [sortInfo, setSortInfo] = useState<any>({});

  const getSortOrder = (field: string): SortOrder => {
    return sortInfo[field];
  };

  const handleSortChange = (
    pagination: TablePaginationConfig,
    filters: Record<string, FilterValue>,
    sorter: SorterResult<any> | SorterResult<any>[]
  ) => {
    // 多列触发排序
    if (Array.isArray(sorter)) {
      const newSortInfo = {};
      sorter.map((item) => {
        const { field, order } = item;
        newSortInfo[field] = order;
      });
      setSortInfo({ ...newSortInfo });
    } else {
      const { field, order } = sorter;

      setSortInfo({
        [field]: order,
      });
    }
  };

  // 处理成字符串的格式  proname asc,contract_name desc
  // const sortStr = useMemo(() => {
  //     let str = ''
  //     Object.keys(sortInfo).map((key) => {
  //         if (!sortInfo[key]) return
  //         if (str) str += ","
  //         str += `${key} ${sortInfo[key] == 'ascend' ? 'asc' : 'desc'}`
  //     })
  //     return str
  // }, [sortInfo])

  const sortArr = useMemo(() => {
    let arr: any[] = [];
    Object.keys(sortInfo).map((key) => {
      if (!sortInfo[key]) return;
      arr.push({
        sortName: key,
        sortOrder: sortInfo[key],
      });
    });
    return arr;
  }, [sortInfo]);

  return [sortArr, getSortOrder, handleSortChange];
};

export default useTableSorter;
